import 'package:image_gallery_saver/image_gallery_saver.dart';
import 'package:permission_handler/permission_handler.dart';
import 'dart:typed_data';

/*
image_gallery_saver: ^2.0.3 (zh) （ 作者两年没更新了，需要手动进入插件目录编辑build.gradle，添加namespace和指定kotlinOptions {jvmTarget = '1.8'}，再删掉自带Menifrest文件里的 package="com.example.imagegallerysaver" ）
permission_handler: ^11.3.1
* */

class Storage {
  // 检查和请求存储权限
  static Future<bool> checkAndRequestPermission() async {
    var status = await Permission.storage.status;
    if (status.isDenied) {
      status = await Permission.storage.request();
    }
    return status.isGranted;
  }

  //保存图片到相册
  static Future<String?> saveImageToGallery(Uint8List imageData, String fileName) async {
    if (!await checkAndRequestPermission()) {
      return '存储权限被拒绝';
    }
    try {
      final result = await ImageGallerySaver.saveImage(imageData, quality: 100, name: fileName);
      if (!result['isSuccess']) {
        return '存储失败';
      }
    } catch (e) {
      return '存储错误: $e';
    }
    return null;
  }
}
